import Vue from 'vue'
import VueRouter from 'vue-router'

// 引入Reg组件
import Reg from '@/views/Reg/Reg.vue'
// 引入Login组件
import Login from '@/views/Login/Login.vue'
// 引入后台主页组件
import Main from '@/views/Main/Main.vue'
// 引入首页组件
import Home from '@/views/Menus/Home/Home.vue'
// 引入基本资料组件
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 配置路由规则
const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  // 后台主页路由规则
  {
    path: '/main',
    component: Main,
    // 路由重定向,登录进来自动跳转首页
    redirect: '/home',
    children: [
      // 首页的子路由
      { path: '/home', component: Home },
      { path: '/user-info', component: UserInfo },
      // 更换头像的子路由规则
      { path: '/user-avatar', component: UserAvatar },
      // 重置密码的子路由规则
      { path: '/user-pwd', component: UserPwd },
      // 文章分类的子路由规则
      { path: '/art-cate', component: ArtCate }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  // 只有后台主页需要访问权限
  if (to.path === '/main') {
    const token = localStorage.getItem('token')
    if (token) {
      // 已登录直接放行
      next()
    } else {
      // 未登录,跳转登录页面
      next('/login')
    }
  } else {
    // 其他页面直接放行
    next()
  }
})

export default router
